package zdy.web.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class download {

	// 上传配置
	private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
	private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
	private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

	public List<String> files;
	public Map<String, String> map;

	
	public void send(HttpServletRequest request, HttpServletResponse response) {
		// 获取文件名
		String filename = request.getParameter("name");
		// 防止读取name名乱码
		try {
			filename = new String(filename.getBytes("iso-8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return ;
		}
		// 在控制台打印文件名
		System.out.println("文件名：" + filename);
		ServletContext context = request.getServletContext();
		// 设置文件MIME类型
		response.setContentType(context.getMimeType(filename));
		// 设置Content-Disposition
		response.setHeader("Content-Disposition", "attachment;filename=" + filename);

		// 获取要下载的文件绝对路径，我的文件都放到WebRoot/download目录下

		String fullFileName = context.getRealPath("/download/" + filename);

		// 输入流为项目文件，输出流指向浏览器
		ServletOutputStream os = null;
		InputStream is = null;
		try {
			is = new FileInputStream(fullFileName);
			os = response.getOutputStream();

			/*
			 * 设置缓冲区 is.read(b)当文件读完时返回-1
			 */
			int len = -1;
			byte[] b = new byte[1024];
			while ((len = is.read(b)) != -1) {
				os.write(b, 0, len);
			}
			is.close();
			os.flush();
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	
	}

}
